package com.yuntsg.nnsfcp.common.intercepter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.front.entity.UserInfo;
import com.yuntsg.nnsfcp.front.mapper.UserInfoMapper;
import com.yuntsg.nnsfcp.service.front.impl.SessionListener;
import com.yuntsg.nnsfcp.service.front.ut.QuickRequestHandler;
import com.yuntsg.nnsfcp.service.front.ut.TokenUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 前台用户登陆拦截器
 *
 * @author ：ljx
 * @date ：Created in 2019/8/2
 */
@Component
@Slf4j
public class ApiSignatureInterceptor extends HandlerInterceptorAdapter {

    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    HttpSession session;
    @Resource
    private TokenUtils tokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        // 当前请求地址
        String requestUrl = request.getRequestURI();
        boolean isTest = false;
        if (StringUtil.isNull(session.getAttribute("fuid"))) {
            boolean exist = isTest;
            if (isTest || exist) {
                log.info("测试服务器进行");
                UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", "18678297353"));
                String token = tokenUtils.createToken(userInfo.getId() + "", userInfo.getName(), userInfo.getPhone(), userInfo.getAccount());
                HttpSession session = request.getSession();
                //存sesion一份
                SessionListener.setSessionByUserInfo(session, userInfo);
                //添加用户登陆在线状态
                SessionListener.addUserLogin(session);
                session.setMaxInactiveInterval(2000);
                session.setAttribute("fuid", userInfo.getId());
            } else {
                //判断有没有token
                String serverTokenStr = request.getHeader("token");
                if (StringUtils.isEmpty(serverTokenStr) || "null".equals(serverTokenStr)) {
                    response.setStatus(401);
                    return false;
                }

                Claims claims = tokenUtils.parsingToken(serverTokenStr);
                if (claims == null) {
                    response.setStatus(401);
                    return false;
                }

                // 频繁点击处理
                if (!QuickRequestHandler.getRequestUrlTime(claims.getId(), requestUrl)) {
                    response.setStatus(204);
                    return false;
                }

                request.setAttribute("u_id", claims.getId());
                session.setAttribute("fuid", claims.getId());
                request.setAttribute("u_Name", claims.getSubject());
                request.setAttribute("u_phone", claims.get("phone"));
                request.setAttribute("u_account", claims.get("account"));
            }
        }


        return true;
    }
}